var $ = require('../../utils/Ajax.js');

// 日历函数
function Calendar(Year, Month) {
  // console.log(Year + " " + Month)

  // 存放天数数组
  var DayArr = [];

  // 当前年
  var Year = Number(Year);

  // 当前月的下标
  var Month = Number(Month) - 1;

  // 获取到下个月的下标
  var Month_ = Month + 1;

  // 用下个月份一号的时间戳减去当月一号的时间戳就等于当月的时间戳
  var TimeStamp = new Date(Year, Month_) - new Date(Year, Month);

  // 用当月的时间戳除去 1000 * 60 * 60 * 24 就得到了当月的天数
  var CurrentDay = TimeStamp / (1000 * 60 * 60 * 24);

  // 获取当月的一号是周几
  var CurrentWeek = new Date(Year, Month, 1).getDay();

  // 获取上个月份
  var TopMonth = Month - 1;

  // 用当前月份一号的时间戳减去上个月份一号的时间戳就等于上个月的时间戳
  var TopTimeStamp = +new Date(Year, Month) - +new Date(Year, TopMonth);

  // 用上个月的时间戳除去 1000 * 60 * 60 * 24 就得到了上个月的天数
  var TopCurrentDay = TopTimeStamp / (1000 * 60 * 60 * 24);


  // 将上个月天数追加到数组里面,判断周是否大于1，否则这个月一号就是周一
  if (CurrentWeek > 0) {
    for (var j = 0; j < CurrentWeek; j++) {
      // 给数组 DayArr 之前插入上个月的几天
      if (Month == 0){
        DayArr.unshift({
          Year: Year - 1,
          Month: 12,
          Day: TopCurrentDay,
          Click: 0,
          Class: 'NoSelect'
        })
      }else{
        DayArr.unshift({
          Year: Year,
          Month: TopMonth + 1,
          Day: TopCurrentDay,
          Click: 0,
          Class: 'NoSelect'
        })
      }
      TopCurrentDay--
    }
  }


  // 将本月天数追加到数组里面
  for (var i = 1; i <= CurrentDay; i++) {
    DayArr.push({
      Year: Year,
      Month: Month + 1,
      Day: i,
      Click: 0,
      Class: 'NoSelect'
    })
  }


  // 日历七列六行，全部展示就是42个，42减去当月天数和上月补充的天数，就得到了下个月补充的天数
  var NextCurrentDay = 42 - CurrentDay - CurrentWeek;
  if (NextCurrentDay > 0) {
    for (var y = 1; y <= NextCurrentDay; y++) {
      // 给数组 DayArr 之后插入上个月的几天
      if (Month == 11){
        DayArr.push({
          Year: Year + 1,
          Month: 1,
          Day: y,
          Click: 0,
          Class: 'NoSelect'
        })
      }else{
        DayArr.push({
          Year: Year,
          Month: Month + 2,
          Day: y,
          Click: 0,
          Class: 'NoSelect'
        })
      }
    }
  }
  // console.log(DayArr)
  return DayArr;
}

// 查询当月可选的天数
function CurrentMonth(that){
  var Year = new Date().getFullYear();
  var Month = new Date().getMonth();
  var Day = new Date().getDate();
  var that = that;
  var Calenda = that.data.Calendar;
  var OptionalTime = that.data.OptionalTime;
  for (var CalendaI = 0; CalendaI < Calenda.length; CalendaI++) {
    for (var OptionalTimeI = 0; OptionalTimeI < OptionalTime.length; OptionalTimeI++) {
      if (Calenda[CalendaI].Year == OptionalTime[OptionalTimeI].Year && Calenda[CalendaI].Month == OptionalTime[OptionalTimeI].Month && Calenda[CalendaI].Day == OptionalTime[OptionalTimeI].Day) {
        if (Calenda[CalendaI].Year == Year){
          if (Calenda[CalendaI].Month >= Month && Calenda[CalendaI].Day >= Day){
            var CalendarClick = 'Calendar[' + CalendaI + '].Click';
            var CalendarClass = 'Calendar[' + CalendaI + '].Class';
            that.setData({
              [CalendarClick]: OptionalTime[OptionalTimeI].Click,
              [CalendarClass]: OptionalTime[OptionalTimeI].Class
            })
          }
        } else if (Calenda[CalendaI].Year > Year){
          var CalendarClick = 'Calendar[' + CalendaI + '].Click';
          var CalendarClass = 'Calendar[' + CalendaI + '].Class';
          that.setData({
            [CalendarClick]: OptionalTime[OptionalTimeI].Click,
            [CalendarClass]: OptionalTime[OptionalTimeI].Class
          })
        }
      }
    }
  }
}


Page({
  data: {
    Year: new Date().getFullYear(),
    Month: new Date().getMonth() + 1,
    Day: new Date().getDate(),
    Calendar: [],
    DAta: [],
    OptionalTime: [],
    DayIndex: null,
    // 人数
    ExperNumber: 1,
    // 选定的日期
    SelectTime: null,
    // 时间
    ExperTime: [],
    // 选定的时间
    ExperTime_: null,
    // 订单ID
    ExperId: null,
    // 订单价格
    ExperPrice: 0,
    // 订单总价
    ExperPrice_: 0,
    // 默认选择时间
    SelectIndex: 0,
    // 消息
    MsgInput: null,
    // 手机号码
    Phone: '',
    PhoneIcon: "../../images/icon_rxg.png",
    PhoneFocus: false,
    PhoneDisabled: true,
    Radio: true,
    // 人数减少按钮
    IncreaseBtn: false,
    // 注意事项
    Careful: null,
    // 按钮禁用
    Disabled: false
  },

  onShow: function () {
    // 判断Token是否存在
    var Token = wx.getStorageSync('Token');
    if (Token == '' || Token == null) {
      wx.switchTab({
        url: '../My/My',
      })
    }

    // 判断用户信息,自动填写手机号码
    var UserInfor = wx.getStorageSync('UserInfor');
    if (UserInfor != null || UserInfor != ''){
      this.setData({
        Phone: UserInfor.user.mobile
      })
    }
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "选择日期"
    });
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FDD436'
    });

    this.setData({
      ExperId: options.Id,
      ExperPrice: options.Price,
      ExperPrice_: options.Price * this.data.ExperNumber,
      DAta: options.DAte.split(","),
      ExperTime: options.Time.split(","),
      Careful: options.Careful
    });

    var Optional = [];
    var OptionalTime = this.data.DAta;
    for (var i = 0; i < OptionalTime.length; i++) {
      var OptionalTime_ = OptionalTime[i];
      var NewOptional = OptionalTime_.split("/");
      Optional.push({
        Year: NewOptional[0],
        Month: NewOptional[1],
        Day: NewOptional[2],
        Click: 1,
        Class: 'OkSelect'
      })
    }

    this.setData({
      Calendar: Calendar(this.data.Year, this.data.Month),
      OptionalTime: Optional,
      ExperTime_: this.data.ExperTime[0]
    })

    // 调用查询当月可选的天数的函数
    CurrentMonth(this);
  },

  // 点击上个月函数
  Per: function () {
    var Year = this.data.Year;
    var Month = this.data.Month;
    --Month;
    if (Month == 0) {
      var Year = Year - 1;
      this.setData({
        Year: Year,
        Month: 12,
        Calendar: Calendar(Year, 12),
      })
    } else {
      this.setData({
        Year: Year,
        Month: Month,
        Calendar: Calendar(Year, Month)
      })
    }

    // 调用查询当月可选的天数的函数
    CurrentMonth(this);
  },

  // 点击下个月函数
  Next: function () {
    var Year = this.data.Year;
    var Month = this.data.Month;
    ++Month;
    if (Month == 13) {
      var Year = Year + 1;
      this.setData({
        Year: Year,
        Month: 1,
        Calendar: Calendar(Year, 1)
      })
    } else {
      this.setData({
        Year: Year,
        Month: Month,
        Calendar: Calendar(Year, Month)
      })
    }
    
    // 调用查询当月可选的天数的函数
    CurrentMonth(this);
  },

  // 点击某一天增加样式
  ClickDay: function(e){
    var ClickDay = e.target.dataset.click;
    var Index = e.target.dataset.index;
    if (ClickDay == 0) {
      wx.showToast({
        title: '不可选',
        icon: 'success',
        duration: 500
      });
    } else {
      var Year = new Date().getFullYear();
      var Month = new Date().getMonth();
      var Day = new Date().getDate();
      var Year_ = e.target.dataset.year_;
      var Month_ = e.target.dataset.month_;
      var Day_ = e.target.dataset.day_;
      this.setData({
        SelectTime: Year_ + "-" + Month_ + "-" + Day_
      })
      var Calenda = this.data.Calendar;
      var OptionalTime = this.data.OptionalTime;
      for (var CalendaI = 0; CalendaI < Calenda.length; CalendaI++) {
        for (var OptionalTimeI = 0; OptionalTimeI < OptionalTime.length; OptionalTimeI++) {
          if (Calenda[CalendaI].Year == OptionalTime[OptionalTimeI].Year && Calenda[CalendaI].Month == OptionalTime[OptionalTimeI].Month && Calenda[CalendaI].Day == OptionalTime[OptionalTimeI].Day) {

            // var CalendarClick = 'Calendar[' + CalendaI + '].Click';
            // var CalendarClass = 'Calendar[' + CalendaI + '].Class';
            // this.setData({
            //   [CalendarClick]: OptionalTime[OptionalTimeI].Click,
            //   [CalendarClass]: OptionalTime[OptionalTimeI].Class
            // })

            if (Calenda[CalendaI].Year == Year) {
              if (Calenda[CalendaI].Month >= Month && Calenda[CalendaI].Day >= Day) {
                var CalendarClick = 'Calendar[' + CalendaI + '].Click';
                var CalendarClass = 'Calendar[' + CalendaI + '].Class';
                this.setData({
                  [CalendarClick]: OptionalTime[OptionalTimeI].Click,
                  [CalendarClass]: OptionalTime[OptionalTimeI].Class
                })
              }
            } else if (Calenda[CalendaI].Year > Year) {
              var CalendarClick = 'Calendar[' + CalendaI + '].Click';
              var CalendarClass = 'Calendar[' + CalendaI + '].Class';
              this.setData({
                [CalendarClick]: OptionalTime[OptionalTimeI].Click,
                [CalendarClass]: OptionalTime[OptionalTimeI].Class
              })
            }

          }
          if (CalendaI == Index) {
            var CalendarClass = 'Calendar[' + CalendaI + '].Class';
            this.setData({
              [CalendarClass]: "Select"
            })
          }
        }
      }
    }
  },

  // 点击减少体验人数
  Increase: function(){
    var ExperNumber = this.data.ExperNumber
    --ExperNumber
    if (ExperNumber == 1 ){
      this.setData({
        IncreaseBtn: false,
        ExperNumber: ExperNumber,
        ExperPrice_: this.data.ExperPrice * ExperNumber
      })
    }else{
      this.setData({
        IncreaseBtn: true,
        ExperNumber: ExperNumber,
        ExperPrice_: this.data.ExperPrice * ExperNumber
      })
    }
  },

  // 点击增加体验人数
  Reduce: function(){
    this.setData({
      IncreaseBtn: true,
      ExperNumber: ++this.data.ExperNumber,
      ExperPrice_: this.data.ExperPrice * this.data.ExperNumber
    })
  },

  // 点击选择时间
  ClickTime: function(e){
    this.setData({
      SelectIndex: e.target.dataset.selecttime,
      ExperTime_: e.target.dataset.selecttime_
    })
  },

  ExperInput: function(e){
    this.setData({
      MsgInput: e.detail.value,
    });
  },

  // 监听
  CompletePhone: function(e){
    var Phone = e.detail.value
    if (Phone.length == 11){
      this.setData({
        Phone: Phone,
        PhoneFocus: false,
        PhoneIcon: "../../images/icon_rxg.png",
        PhoneDisabled: true
      });
      wx.showToast({
        title: '输入完成',
        icon: 'success',
        duration: 3000
      });
    }
  },

  // 点击编辑手机号码
  ClickPhoneIcon: function(){
    this.setData({
      PhoneFocus: true,
      PhoneDisabled: false
    });
  },

  // 阅读退款协议
  Radio: function(){
    this.setData({
      Radio:!this.data.Radio
    })
  },

  // 提交订单
  SubmitOrder: function () {
    var that = this;
    this.setData({
      Disabled: true
    })
    if(this.data.Radio){
      var Phone = this.data.Phone;
      var ExperId = this.data.ExperId;
      var Phone = this.data.Phone;
      var ExperPrice = this.data.ExperPrice;
      var ExperPrice_ = this.data.ExperPrice_;
      var ExperNumber = this.data.ExperNumber;
      var Date = this.data.SelectTime;
      var Time = this.data.ExperTime_;

      if (Date == null) {
        that.setData({
          Disabled: false
        })
        wx.showToast({
          title: '日期不能为空',
          icon: 'none',
          image: '../../images/err.png',
          duration: 3000
        });
      } else if (Phone == '' || Phone == null) {
        that.setData({
          Disabled: false
        })
        wx.showToast({
          title: '手机号码不能为空',
          icon: 'none',
          image: '../../images/err.png',
          duration: 3000
        });
      }else{
        $.Ajax("api/x_make_order", "POST", {
          obj_id: ExperId,
          order_type: 1,
          mobile: Phone,
          order_amount: ExperPrice_,
          obj_num: ExperNumber,
          obj_price: Number(ExperPrice),
          date: Date,
          time: Time,
          remarks: that.data.MsgInput
        }, function (res) {
          console.log(res)
          if (res.s) {
            that.setData({
              Disabled: false
            })
            wx.requestPayment({
              timeStamp: res.d.config.timestamp,
              nonceStr: res.d.config.nonceStr,
              package: res.d.config.package,
              signType: res.d.config.signType,
              paySign: res.d.config.paySign,
              success(ress) {
                wx.navigateTo({
                  url: '../PaymentOk/PaymentOk?Many=' + ExperPrice_,
                })
              },
              fail: function (ress) {
                $.Ajax("api/x_d_order", "POST", {
                  order_sn: res.d.order_sn
                }, function (res) {
                  console.log(res)
                })
              }
            })
          } else {
            that.setData({
              Disabled: false
            })
            wx.showToast({
              title: res.m,
              icon: 'none',
              duration: 3000
            });
          }
        });
      }
    } else {
      that.setData({
        Disabled: false
      })
      wx.showToast({
        title: '请先阅读协议',
        icon: 'success',
        image: "../../images/err.png",
        duration: 3000
      });
    }
  }
})